<template>
  <div class="comment-manage">
    <div class="header">
      <h2>评论管理</h2>
      <div class="search-box">
        <el-input
          v-model="searchParams.goodName"
          placeholder="商品名称"
          style="width: 200px; margin-right: 10px;"
          clearable
        />
        <el-input
          v-model="searchParams.userName"
          placeholder="用户名"
          style="width: 200px; margin-right: 10px;"
          clearable
        />
        <el-select
          v-model="searchParams.rating"
          placeholder="评分"
          style="width: 120px; margin-right: 10px;"
          clearable
        >
          <el-option label="5星" :value="5" />
          <el-option label="4星" :value="4" />
          <el-option label="3星" :value="3" />
          <el-option label="2星" :value="2" />
          <el-option label="1星" :value="1" />
        </el-select>
        <el-button type="primary" @click="searchComments">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
    </div>

    <div class="table-container">
      <el-table :data="comments" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="goodName" label="商品名称" width="200" />
        <el-table-column prop="userName" label="用户" width="120">
          <template slot-scope="scope">
            {{ scope.row.isAnonymous ? '匿名用户' : scope.row.userName }}
          </template>
        </el-table-column>
        <el-table-column prop="rating" label="评分" width="100">
          <template slot-scope="scope">
            <el-rate
              v-model="scope.row.rating"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}"
            />
          </template>
        </el-table-column>
        <el-table-column prop="content" label="评论内容" width="300">
          <template slot-scope="scope">
            <div class="comment-content">
              {{ scope.row.content }}
              <div v-if="scope.row.images" class="comment-images">
                <img
                  v-for="(image, index) in scope.row.images.split(',')"
                  :key="index"
                  :src="image"
                  alt="评论图片"
                  class="comment-image"
                  @click="previewImage(image)"
                />
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="评论时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="replyContent" label="商家回复" width="200">
          <template slot-scope="scope">
            <div v-if="scope.row.replyContent" class="reply-content">
              {{ scope.row.replyContent }}
              <div class="reply-time">{{ formatDate(scope.row.replyTime) }}</div>
            </div>
            <span v-else class="no-reply">未回复</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="small"
              @click="openReplyDialog(scope.row)"
              :disabled="scope.row.replyContent"
            >
              {{ scope.row.replyContent ? '已回复' : '回复' }}
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="deleteComment(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </div>

    <!-- 回复对话框 -->
    <el-dialog
      title="回复评论"
      :visible.sync="replyDialogVisible"
      width="500px"
      @close="closeReplyDialog"
    >
      <div class="reply-dialog">
        <div class="original-comment">
          <h4>原评论：</h4>
          <div class="comment-info">
            <p><strong>用户：</strong>{{ currentComment.isAnonymous ? '匿名用户' : currentComment.userName }}</p>
            <p><strong>商品：</strong>{{ currentComment.goodName }}</p>
            <p><strong>评分：</strong>
              <el-rate
                v-model="currentComment.rating"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}"
              />
            </p>
            <p><strong>内容：</strong>{{ currentComment.content }}</p>
          </div>
        </div>
        <div class="reply-form">
          <h4>商家回复：</h4>
          <el-input
            type="textarea"
            v-model="replyContent"
            placeholder="请输入回复内容..."
            :rows="4"
            maxlength="500"
            show-word-limit
          />
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeReplyDialog">取消</el-button>
        <el-button type="primary" @click="submitReply" :loading="replyLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="imagePreviewVisible"
      width="60%"
      center
    >
      <img :src="previewImageUrl" alt="预览图片" style="width: 100%; max-height: 500px; object-fit: contain;" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'CommentManage',
  data() {
    return {
      comments: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchParams: {
        goodName: '',
        userName: '',
        rating: null
      },
      replyDialogVisible: false,
      currentComment: {},
      replyContent: '',
      replyLoading: false,
      imagePreviewVisible: false,
      previewImageUrl: ''
    }
  },
  mounted() {
    this.loadComments()
  },
  methods: {
    async loadComments() {
      this.loading = true
      try {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          ...this.searchParams
        }
        console.log('请求参数:', params)
        const response = await this.request.get('/api/comment/page', { params })
        console.log('响应数据:', response)
        this.comments = response.data.records
        this.total = response.data.total
      } catch (error) {
        console.error('加载评论失败:', error)
        this.$message.error('加载评论失败: ' + (error.response?.data?.msg || error.message))
      } finally {
        this.loading = false
      }
    },
    searchComments() {
      this.currentPage = 1
      this.loadComments()
    },
    resetSearch() {
      this.searchParams = {
        goodName: '',
        userName: '',
        rating: null
      }
      this.currentPage = 1
      this.loadComments()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.loadComments()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadComments()
    },
    openReplyDialog(comment) {
      this.currentComment = comment
      this.replyContent = ''
      this.replyDialogVisible = true
    },
    closeReplyDialog() {
      this.replyDialogVisible = false
      this.currentComment = {}
      this.replyContent = ''
    },
    async submitReply() {
      if (!this.replyContent.trim()) {
        this.$message.warning('请输入回复内容')
        return
      }
      
      this.replyLoading = true
      try {
        await this.request.post(`/api/comment/reply/${this.currentComment.id}`, {
          replyContent: this.replyContent
        })
        this.$message.success('回复成功')
        this.closeReplyDialog()
        this.loadComments()
      } catch (error) {
        this.$message.error('回复失败')
      } finally {
        this.replyLoading = false
      }
    },
    async deleteComment(commentId) {
      try {
        await this.$confirm('确定要删除这条评论吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await this.request.delete(`/api/comment/${commentId}`)
        this.$message.success('删除成功')
        this.loadComments()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },
    previewImage(imageUrl) {
      this.previewImageUrl = imageUrl
      this.imagePreviewVisible = true
    },
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }
  }
}
</script>

<style scoped>
.comment-manage {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #333;
}

.search-box {
  display: flex;
  align-items: center;
}

.table-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.comment-content {
  line-height: 1.5;
}

.comment-images {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.comment-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #ddd;
}

.comment-image:hover {
  border-color: #409eff;
}

.reply-content {
  background: #f5f7fa;
  padding: 8px;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.reply-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.no-reply {
  color: #999;
  font-style: italic;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.reply-dialog {
  max-height: 400px;
  overflow-y: auto;
}

.original-comment {
  margin-bottom: 20px;
  padding: 15px;
  background: #f9f9f9;
  border-radius: 6px;
}

.original-comment h4 {
  margin: 0 0 10px 0;
  color: #333;
}

.comment-info p {
  margin: 8px 0;
  color: #666;
}

.reply-form h4 {
  margin: 0 0 10px 0;
  color: #333;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .search-box {
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .comment-manage {
    padding: 10px;
  }
}
</style> 